import React, { useState, useRef, useEffect } from 'react';
import { Button, Radio, Space, Tabs } from 'antd';
import './tab.css'

/* 

// !!!! 项目在容器中露出的高度/项目高度 = threshold或它数组中某一个值时，触发IntersectionObserver传参上的回调
*/




const App = () => {
  const contentRef = useRef(null);
  const [activeKey, activeKeySet] = useState('tab1');
  const [tablist, tablistSet] = useState([{ label: 'tab1', key: 'tab1' }, { label: 'tab2', key: 'tab2' }, { label: 'tab3', key: 'tab3' }]);
  const tablistDom = {}

  useEffect(() => {
    // 定义根元素，这里我们将整个文档的视口作为根元素
    const root = contentRef.current;
    // 定义其他配置选项
    const options = {
      root: root, // 设置根元素
      rootMargin: '0px', // 设置边界偏移，这里为0，表示不偏移
      threshold: 0.1 // 设置阈值，这里为0.5，表示当目标元素与根元素交叉的比例达到50%时触发回调, 
    };
    // 创建 IntersectionObserver 实例
    const observer = new IntersectionObserver(function (entries) {
      // 视口内的元素
      console.log('entries', entries)
      // entries 是一个数组，包含了所有被观察元素的交叉状态
      // entries.sort((prev,next) => next.intersectionRatio - prev.intersectionRatio)
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const key = entry.target.getAttribute('data-key')
          activeKeySet(key)
        } else {
          // 监测到某一个元素从视口中消失
        }
      });
    }, options);
    console.log('tablistDom', tablistDom)
    Object.keys(tablistDom).forEach(key => {

      observer.observe(tablistDom[key]);
    })
    // 开始观察
    return () => {
      // console.log('1111',1111)
      observer.disconnect()
    }
  }, [tablist])
  return (
    <>

      <Button onClick={() => {
        let newTab = { label: `tab${tablist.length + 1}`, key: `tab${tablist.length + 1}` }
        tablistSet([...tablist, newTab])
      }}>增加</Button>
      <Tabs
        tabPosition={'top'}
        activeKey={activeKey}
        onChange={key => activeKeySet(key)}
        onTabClick={(key) => {
          tablistDom[key].scrollIntoView({ behavior: 'smooth' })
        }}
        items={tablist.map(({ label, key }, i) => {
          return {
            label,
            key,
          };
        })}
      />
      <div className='content' ref={contentRef}>
        {tablist.map(({ label, key }, i) => {
          return <div className='key' key={key} data-key={key} ref={ref => tablistDom[key] = ref} style={{ height: `${400 + i * 150}px`, border: `1px solid #CCC` }}>{label}</div>
        })}
      </div>
    </>
  );
};
export default App;



